import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Table, Button, Modal, Form, Input, Radio, Row, Col, Select, Spin, message } from 'antd';
import style from './systemMenu.less';
import APP from "@/components/Tool/BaseAPP";

const FormItem = Form.Item;
const Option = Select.Option;

/**
 *  编辑窗口
 * @Author 肖家添
 * @Date 2019/5/11 19:26
 */
const CollectionCreateForm = Form.create()(props => {
    let {
        visible,
        onCancel,
        onCreate,
        form,
        systemMenu,
        randomStr,
        defaultData,
        submitLoading,
    } = props;
    const { getFieldDecorator } = form;
    const systemMenus = systemMenu.map(item => (
        <Option key={item.id} value={item.id}>
            {item.name}
        </Option>
    ));

    const havaDefaultVal = Object.keys(defaultData).length;

    if (havaDefaultVal > 0) {
        randomStr = defaultData.code;
    }

    return (
        <Modal
            visible={visible}
            title="编辑菜单"
            okText="保存"
            onCancel={onCancel}
            onOk={onCreate}
            confirmLoading={submitLoading}
        >
            <Form layout="vertical">
                {getFieldDecorator('id', {
                    initialValue: defaultData.id,
                })(<Input type="hidden" readOnly/>)}
                <Row gutter={18}>
                    <Col span={12}>
                        <FormItem label="编码">
                            {getFieldDecorator('code', {
                                initialValue: randomStr,
                                rules: [{ required: true, message: '请输入编码' }],
                            })(<Input readOnly/>)}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem label="名称">
                            {getFieldDecorator('name', {
                                initialValue: defaultData.name,
                                rules: [{ required: true, message: '请输入菜单名称' }],
                            })(<Input/>)}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem label="路由地址">
                            {getFieldDecorator('jsArray', {
                                initialValue: defaultData.jsArray,
                                rules: [{ required: true, message: '请输入路由地址' }],
                            })(<Input/>)}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem label="国际化参数">
                            {getFieldDecorator('params', {
                                initialValue: defaultData.params,
                                rules: [{ required: true, message: '请输入国际化参数' }],
                            })(<Input/>)}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem label="图标">
                            {getFieldDecorator('iconCls', {
                                initialValue: defaultData.iconCls,
                            })(<Input/>)}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem label="排序">
                            {getFieldDecorator('orderNo', {
                                initialValue: defaultData.orderNo,
                                rules: [{ required: true, message: '请输入序号' }],
                            })(<Input/>)}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem label="备注">
                            {getFieldDecorator('remark', {
                                initialValue: defaultData.remark,
                            })(<Input/>)}
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem label="父菜单">
                            {getFieldDecorator('pid', {
                                initialValue: defaultData.pid == null ? 0 : defaultData.pid,
                            })(
                                <Select>
                                    <Option value={0}>无</Option>
                                    {systemMenus}
                                </Select>,
                            )}
                        </FormItem>
                        {/*return <Option value={item.id}>{item.name}</Option>;*/}
                    </Col>
                    <Col span={24}>
                        <FormItem>
                            {getFieldDecorator('isenabled', {
                                initialValue: defaultData.isenabled == null ? '1' : defaultData.isenabled + '',
                            })(
                                <Radio.Group>
                                    <Radio value="1">上架</Radio>
                                    <Radio value="0">下架</Radio>
                                </Radio.Group>,
                            )}
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </Modal>
    );
});

@connect(({ systemMenuModel }) => ({
  systemMenuModel
}))
class systemMenu extends Component {
    state = {
        selectedRowKeys: [], //复选框选中的行键
        editModalVisible: false, //编辑窗口显示隐藏
        newestMenuCode: '', //新菜单的Code唯一值
        loading: false, //加载层
        editModalDefaultData: {}, //修改菜单时需要修改的数据
        editModalSubmitLoading: false,
        menuData: [],
    };

    componentDidMount() {
        const { dispatch } = this.props;
        const thisCtx = this;

        thisCtx.setState({ loading: true });

        dispatch({
            type: 'systemMenuModel/fetch',
            callback: function(data) {
                console.log("data->", data);
                thisCtx.setState({
                    loading: false,
                    selectedRowKeys: [],
                    menuData: data.datas,
                });

                if (!data.success) {
                    message.error(data.msg);
                }
            },
        });


        this.getNewestMenuCode();
    }

    /**
     *  复选框选择事件
     * @Author 肖家添
     * @Date 2019/5/11 17:28
     */
    onCheckboxSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };

    /**
     *  显示/隐藏编辑窗口
     * @Author 肖家添
     * @Date 2019/5/11 12:25
     */
    editModalHandler(editModalVisible) {
        const form = this.form;

        form.resetFields();

        this.setState({ editModalVisible });
        this.setState({ editModalDefaultData: {} });
    }

    /**
     *  编辑
     * @Author 肖家添
     * @Date 2019/5/11 17:29
     */
    editButtonClick() {
        const selectedRowKeys = this.state.selectedRowKeys;

        if (selectedRowKeys.length == 1) {
            this.editModalHandler(true);

            let id = selectedRowKeys[0];

            const { menuData } = this.state;

            if (menuData != null) {
                for (let i = 0; i < menuData.length; i++) {
                    if (menuData[i].id == id) {
                        this.setState({ editModalDefaultData: menuData[i] });

                        break;
                    }
                }
            }
        } else {
            message.info('请选择一条数据');
        }
    }

    /**
     *  编辑提交
     * @Author 肖家添
     * @Date 2019/5/11 12:25
     */
    editModalHandleCreate = () => {
        const form = this.form;
        const thisCtx = this;

        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            thisCtx.setState({ editModalSubmitLoading: true });

            values.menuID = -1;
            values.loadType = 2;
            values.type = 2;

            const { dispatch } = this.props;

            let url = values.id != null ? 'systemMenuModel/update' : 'systemMenuModel/add';

            dispatch({
                type: url,
                payload: values,
                callback: function(data) {
                    thisCtx.setState({ editModalSubmitLoading: false });

                    if (data.success) {
                        thisCtx.editModalHandler(false);

                        message.info('保存成功');

                        thisCtx.componentDidMount();
                    } else {
                        message.error(data.msg);
                    }
                },
            });
        });
    };

    /**
     *  表单引用
     * @Author 肖家添
     * @Date 2019/5/11 12:25
     */
    editModalFormRef = form => {
        this.form = form;
    };

    /**
     *  上架/下架/删除
     * @Author 肖家添
     * @Date 2019/5/11 17:53
     */
    statusButtonClick(isEnabled) {
        const selectedRowKeys = this.state.selectedRowKeys;

        if (selectedRowKeys.length > 0) {
            let thisCtx = this;
            const { dispatch } = this.props;

            let requestData = 'isenabled=' + isEnabled;
            let selectedLength = selectedRowKeys.length;

            for (let i = 0; i < selectedLength; i++) {
                requestData += '&id=' + selectedRowKeys[i];
            }

            thisCtx.setState({ loading: true });

            dispatch({
                type: 'systemMenuModel/updateStatus',
                payload: { datas: requestData },
                callback: function(data) {
                    thisCtx.setState({ loading: false });

                    if (data.success) {
                        message.info('提交成功');

                        thisCtx.componentDidMount();
                    } else {
                        message.error(data.msg);
                    }
                },
            });
        } else {
            message.info('请选择一条数据');
        }
    }

    /**
     *  更新新菜单的Code
     * @Author 肖家添
     * @Date 2019/5/11 15:41
     */
    getNewestMenuCode = function() {
        const randomStr = "M" + (
            moment().format("YYYYMMDDHHmm")
        ) + (
            Math.floor(Math.random() * 100000)
        );

        this.setState({ newestMenuCode: randomStr });
    };

    render() {
        const { menuData } = this.state;

        let { selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onCheckboxSelectChange,
        };

        const hasSelected = selectedRowKeys.length > 0;

        let data = [];
        if (menuData != null && menuData != undefined) {
            data = menuData;
        }

        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <div style={{ marginBottom: 16 }} className={style.menuButtonsDiv}>
                        <Button type="primary" onClick={() => this.editModalHandler(true)}>
                            新增
                        </Button>
                        <Button type="primary" onClick={() => this.editButtonClick()}>
                            编辑
                        </Button>
                        <Button type="primary" onClick={() => this.statusButtonClick(1)}>
                            上架
                        </Button>
                        <Button type="primary" onClick={() => this.statusButtonClick(0)}>
                            下架
                        </Button>
                        <Button type="primary" onClick={() => this.statusButtonClick(-1)}>
                            删除
                        </Button>
                        <span style={{ marginLeft: 8 }}>
              {hasSelected ? `已选中 ${selectedRowKeys.length} 项` : ''}
            </span>
                    </div>
                    <Table
                        onRow={record => {
                            return {
                                onClick: event => {
                                    event.currentTarget.getElementsByClassName('ant-checkbox-wrapper')[0].click();
                                },
                            };
                        }}
                        rowKey={data => `${data.id}`}
                        rowSelection={rowSelection}
                        columns={this.columns}
                        dataSource={data}
                        bordered={true}
                        pagination={{
                            showTotal: total => `共 ${total} 条数据`,
                        }}
                    />

                    <CollectionCreateForm
                        ref={this.editModalFormRef}
                        visible={this.state.editModalVisible}
                        onCancel={() => this.editModalHandler(false)}
                        onCreate={this.editModalHandleCreate}
                        systemMenu={data}
                        randomStr={this.state.newestMenuCode}
                        defaultData={this.state.editModalDefaultData}
                        submitLoading={this.state.editModalSubmitLoading}
                    />
                </Spin>
            </div>
        );
    }



    /**
     *  表格列
     * @Author 肖家添
     * @Date 2019/5/11 19:26
     */
    columns = [
        {
            title: '编码',
            dataIndex: 'code',
        },
        {
            title: '菜单名称',
            dataIndex: 'name',
        },
        {
            title: '菜单样式',
            dataIndex: 'iconCls',
        },
        {
            title: '父级菜单',
            dataIndex: 'pid',
            render: (text) => {
                if (!APP.isValidObj(text) || text === 0) {
                    return '无';
                } else {
                    const menuData = this.state.menuData;
                    if (menuData != null) {
                        for (let i = 0; i < menuData.length; i++) {
                            if (menuData[i].id === text) {
                                return menuData[i].name;
                            }
                        }
                    }
                }
            },
        },
        {
            title: '路由地址',
            dataIndex: 'jsArray',
        },
        {
            title: '附加参数',
            dataIndex: 'params',
        },
        {
            title: '排序',
            dataIndex: 'orderNo',
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '可用',
            dataIndex: 'isenabled',
            render: function(text) {
                if (text === 1) {
                    return '上架';
                } else {
                    return '下架';
                }
            },
        },
        {
            title: '创建日期',
            dataIndex: 'createTime',
            render: val => <span>{val != null ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''}</span>,
        },
        {
            title: '修改人姓名',
            dataIndex: 'modifierUser.empName',
        },
        {
            title: '修改时间',
            dataIndex: 'modifytime',
            render: val => <span>{val != null ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''}</span>,
        },
    ];
}

export default systemMenu;
